//
//  LoginController.m
//  ELife
//
//  Created by xiaozhi on 11-5-17.
//  Copyright 2011Âπ?__MyCompanyName__. All rights reserved.
//

#import "LoginController.h"
#import "UIViewUtil.h"
#import "ELifeAppDelegate.h"
#import "GDataXMLNode.h"
#import "RegisterController.h"
#import "GTMBase64.h"
#import "AlertView.h"
#import "M13UserDefaults.h"

@implementation LoginController

@synthesize userName, password;

BOOL _savePasswordTag;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [userName release];
    [password release];
    
    [super dealloc];
}


- (id) init:(id)target
{
    if (self=[super init]) {
        
    }
    delegate = target;
    return self;
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIViewUtil getCommonBg];
    
    [userName setDelegate:self];
    [password setDelegate:self];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)inputFinished
{
    [password resignFirstResponder];
    [userName resignFirstResponder];
}

#pragma mark login and register

- (NSString *) md5:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, strlen(cStr), result);
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}
//login
- (IBAction)elifeLogin
{
    ELifeAppDelegate * app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍候"];
    
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@user.php?", [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil]]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:4];
    [param setObject:@"login" forKey:@"action"];
    [param setObject:[userName text] forKey:@"username"];
    
//    NSString *passwordMD5 = [self md5:[password text]];
    
    [param setObject:[password text] forKey:@"password"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
}

//register
- (void)elifeRegister
{
    RegisterController* regCon = [[RegisterController alloc] initWithNibName:@"RegisterController" bundle:nil];
    [self.navigationController pushViewController:regCon animated:YES];
    [regCon release];
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)signSavePassword:(id)sender
{
    _savePasswordTag = !_savePasswordTag;
    
    UIImage *radioButtonNormal = [UIImage imageNamed:@"radiobutton_unselected.png"];
    UIImage *radioButtonFocus = [UIImage imageNamed:@"radiobutton_selected.png"];
    
    UIImage *img = radioButtonNormal;
    if (_savePasswordTag) {
        img = radioButtonFocus;
    }
    
    UIButton *radioButton = (UIButton *)sender;
    [radioButton setImage:img forState:UIControlStateNormal];
}

- (void)iRequestFinished:(NSData *)request
{
    [[ELifeAppDelegate App] hideProgressDialog];
  
    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[GTMBase64 decodeData:request] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", retStr);
    [retStr release];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:request] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    NSArray* children = [rootElement children];
      NSLog(@"--------rootElement:%@", rootElement);
    
    GDataXMLElement* headElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    
    NSInteger returnCode = [[[[headElement elementsForName:@"returncode"]objectAtIndex:0] stringValue] intValue];
    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    NSLog(@"--------body:--------\n%@", bodyElement);
    
    if (returnCode == 0){
        NSString* uid = [[[bodyElement elementsForName:@"uid"]objectAtIndex:0] stringValue];
        [M13UserDefaults setUserDefaults:[NSArray arrayWithObjects:userName.text, password.text, uid, nil] defaultName:USERINFO_NAMEANDPASSWORD];
        
        [delegate registerOver:userName.text];
        [self.navigationController popViewControllerAnimated:YES];
    }else if (returnCode == -102)
    {
        [AlertView showAlert:@"用户名密码错误"];
        
    }else {
        [AlertView showAlert:@"登录失败"];
    }
    [userName resignFirstResponder];
    [password resignFirstResponder];

    [doc release];
    
}

- (void)iRequestFailed
{
    
}

#pragma mark text???
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
	return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
	[textField resignFirstResponder];
	return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
	[textField resignFirstResponder];
	return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
	[textView resignFirstResponder];
	return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    return YES;
}
@end
